package com.pets.springboot_petshop.controller;

import com.pets.springboot_petshop.entity.*;
import com.pets.springboot_petshop.pojo.Result;
import com.pets.springboot_petshop.service.AppointmentslotService;
import com.pets.springboot_petshop.service.ServiceappointmentService;
import com.pets.springboot_petshop.service.UserService;
import com.pets.springboot_petshop.util.JwtUtil;
import com.pets.springboot_petshop.util.OrderNumberUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.List;
import java.util.Map;

/**
 * @Author: wxk
 * @Email: 2089967794@qq.com
 * @Date: 2024/10/14 下午4:37 周一
 * @Description: 用户服务预约控制层
 */
@RestController
@RequestMapping("/Serviceappointment")
public class ServiceappointmentController {
    @Autowired
    private ServiceappointmentService serviceappointmentService;
    @Autowired
    private AppointmentslotService appointmentslotService;
    @Autowired
    private UserService userService;

    //id，通过id查询
    @GetMapping("/select")
    private Result select(@RequestParam int id) {
       Serviceappointment serviceappointment = serviceappointmentService.select(id);
        if (serviceappointment == null) {
            // 如果列表为空或为null，返回错误状态
            return Result.error("没有找到相关记录");
        } else {
            // 如果列表不为空，返回产品列表
            return Result.success(serviceappointment);
        }
    }
    //appointmentslot_id查询
    @GetMapping("/selectappointmentslot_id")
    private Result selectappointmentslot_id(@RequestParam int appointmentslot_id) {
        List<Serviceappointment> serviceappointment = serviceappointmentService.selectappointmentslot_id(appointmentslot_id);
        if (serviceappointment == null || serviceappointment.isEmpty()) {
            // 如果列表为空或为null，返回错误状态
            return Result.error("没有找到相关记录");
        } else {
            // 如果列表不为空，返回产品列表
            return Result.success(serviceappointment);
        }
    }
    //uusername查询
    @GetMapping("/selectuser_id")
    private Result selectuser_id(@RequestHeader(name = "Authorization") String token) {
        // 根据令牌查询相应的用户信息
        Map<String,Object> map = JwtUtil.parseToken(token);
        int user_id = (int) map.get("id");
        // 检查用户是否存在
        User user = userService.select(user_id);
        if (user == null) {
            return Result.error("用户不存在");
        } else {
            List<Serviceappointment> serviceappointment = serviceappointmentService.selectuser_id(user_id);
            if (serviceappointment == null || serviceappointment.isEmpty()) {
                // 如果列表为空或为null，返回错误状态
                return Result.error("没有找到相关记录");
            } else {
                // 如果列表不为空，返回产品列表
                return Result.success(serviceappointment);
            }
        }
    }
    // 获取年度每个月的总盈利
    @GetMapping("/selectMonthlyProfit")
    public Result getMonthlyProfit(@RequestParam int year) {
        List<MonthlyProfit> monthlyProfits = serviceappointmentService.selectMonthlyProfit(year);
        return Result.success(monthlyProfits);
    }
    // 获取当月每天的盈利
    @GetMapping("/selectDailyProfit")
    public Result getDailyProfit(@RequestParam int year, @RequestParam int month) {
        List<DailyProfit> dailyProfits = serviceappointmentService.selectDailyProfit(year, month);
        return Result.success(dailyProfits);
    }
    //service_name查询
    @GetMapping("/selectname")
    private Result selectname(@RequestParam String name) {
        List<Serviceappointment> serviceappointment = serviceappointmentService.selectname(name);
        if (serviceappointment == null || serviceappointment.isEmpty()) {
            // 如果列表为空或为null，返回错误状态
            return Result.error("没有找到相关记录");
        } else {
            // 如果列表不为空，返回产品列表
            return Result.success(serviceappointment);
        }
    }
    //List<Serviceappointment> selectstatus(int status);
    @GetMapping("/selectstatus")
    private Result selectstatus(@RequestParam String status) {
        List<Serviceappointment> serviceappointment = serviceappointmentService.selectstatus(status);
        if (serviceappointment == null || serviceappointment.isEmpty()) {
            // 如果列表为空或为null，返回错误状态
            return Result.error("没有找到相关记录");
        } else {
            // 如果列表不为空，返回产品列表
            return Result.success(serviceappointment);
        }
    }
    //模糊查询订单编号
    @GetMapping("selectordernumber")
    private Result selectordernumber(@RequestParam int ordernumber) {
        // 获取订单
        List<Serviceappointment> selectordernumber = serviceappointmentService.selectordernumber(ordernumber);
        if (selectordernumber != null) {
            return Result.success(selectordernumber);
        } else {
            return Result.error("获取失败");
        }
    }
    //查询所有
    @GetMapping("/findAll")
    private Result findAll() {
        List<Serviceappointment> services = serviceappointmentService.findAll();
        if(services == null || services.isEmpty()){
            return Result.error("获取失败");
        }else {
            return Result.success(services);
        }
    }
    // 根据日期查询
    @GetMapping("/selectOrder")
    public Result selectOrder(@RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate date) {
        // 获取订单
        List<Serviceappointment> serviceappointments = serviceappointmentService.selectOrder(date);
        if (serviceappointments != null) {
            return Result.success(serviceappointments);
        } else {
            return Result.error("获取失败");
        }
    }
    //添加
    @PostMapping("/add")
    private Result add(@RequestBody Serviceappointment serviceappointment, @RequestHeader(name = "Authorization") String token) {
        // 根据令牌查询相应的用户信息
        Map<String,Object> map = JwtUtil.parseToken(token);
        int user_id = (int) map.get("id");
        // 检查用户是否存在
        User user = userService.select(user_id);
        if (user == null) {
            return Result.error("用户不存在");
        } else {
            serviceappointment.setUser_id(user_id);
            serviceappointment.setStatus("未签到");
            serviceappointment.setDiscount(user.getDiscount());
            // 生成订单编号
            String orderNumber = OrderNumberUtil.generateOrderNumber();
            serviceappointment.setOrdernumber(orderNumber);

            // 首先插入Serviceappointment记录
            int insertResult = serviceappointmentService.add(serviceappointment);
            if (insertResult > 0) {
                // 获取Serviceappointment中的appointmentslot_id
                Integer appointmentslotId = serviceappointment.getAppointmentslot_id();
                int serviceappointment_id = serviceappointment.getId();
                // 使用appointmentslot_id查询Appointmentslot对象
                Appointmentslot appointmentslot = appointmentslotService.selectappointmentslot(appointmentslotId);
                if (appointmentslot != null) {
                    // 减少available_spots的数量
                    int newAvailableSpots = appointmentslot.getAvailable_spots() - 1;
                    appointmentslot.setAvailable_spots(newAvailableSpots);

                    // 更新Appointmentslot对象
                    int updateResult = appointmentslotService.updateAppointmentslotById(appointmentslot);
                    if (updateResult > 0) {
                        Serviceappointment serviceappointment1 = new Serviceappointment();
                        serviceappointment1.setId(serviceappointment_id);
                        return Result.success(serviceappointment1);
                    } else {
                        return Result.error("更新Appointmentslot失败");
                    }
                } else {
                    return Result.error("未找到对应的Appointmentslot记录");
                }
            } else {
                return Result.error("新增失败");
            }
        }
    }
    //管理员添加
    @PostMapping("/adminadd")
    private Result adminadd(@RequestBody Serviceappointment serviceappointment) {
        String email = serviceappointment.getEmail();
        User user = userService.findByUseremail(email);
        if (user == null) {
            String username = serviceappointment.getUsername();
            String phone = serviceappointment.getPhone();
            userService.addadmin(username, phone, email);

            User user1 = userService.findByUseremail(email);
            if (user1 == null) {
                return Result.error("订单失败");
            }
            int user_id = user1.getId();
            serviceappointment.setUser_id(user_id);
            serviceappointment.setStatus("未签到");
            String orderNumber = OrderNumberUtil.generateOrderNumber();
            serviceappointment.setOrdernumber(orderNumber);
            // 首先插入Serviceappointment记录
            int insertResult = serviceappointmentService.add(serviceappointment);
            if (insertResult > 0) {
                // 获取Serviceappointment中的appointmentslot_id
                Integer appointmentslotId = serviceappointment.getAppointmentslot_id();
                int serviceappointment_id = serviceappointment.getId();
                // 使用appointmentslot_id查询Appointmentslot对象
                Appointmentslot appointmentslot = appointmentslotService.selectappointmentslot(appointmentslotId);
                if (appointmentslot != null) {
                    // 减少available_spots的数量
                    int newAvailableSpots = appointmentslot.getAvailable_spots() - 1;
                    appointmentslot.setAvailable_spots(newAvailableSpots);

                    // 更新Appointmentslot对象
                    int updateResult = appointmentslotService.updateAppointmentslotById(appointmentslot);
                    if (updateResult > 0) {
                        Serviceappointment serviceappointment1 = serviceappointmentService.select(serviceappointment_id);

                        return Result.success(serviceappointment1);
                    } else {
                        return Result.error("更新Appointmentslot失败");
                    }
                } else {
                    return Result.error("未找到对应的Appointmentslot记录");
                }
            } else {
                return Result.error("新增失败");
            }
        } else {

            int user_id = user.getId();
            serviceappointment.setUser_id(user_id);
            serviceappointment.setStatus("未签到");
            String orderNumber = OrderNumberUtil.generateOrderNumber();
            serviceappointment.setOrdernumber(orderNumber);
            // 首先插入Serviceappointment记录
            int insertResult = serviceappointmentService.add(serviceappointment);
            if (insertResult > 0) {
                // 获取Serviceappointment中的appointmentslot_id
                Integer appointmentslotId = serviceappointment.getAppointmentslot_id();
                int serviceappointment_id = serviceappointment.getId();
                // 使用appointmentslot_id查询Appointmentslot对象
                Appointmentslot appointmentslot = appointmentslotService.selectappointmentslot(appointmentslotId);
                if (appointmentslot != null) {
                    // 减少available_spots的数量
                    int newAvailableSpots = appointmentslot.getAvailable_spots() - 1;
                    appointmentslot.setAvailable_spots(newAvailableSpots);

                    // 更新Appointmentslot对象
                    int updateResult = appointmentslotService.updateAppointmentslotById(appointmentslot);
                    if (updateResult > 0) {
                        Serviceappointment serviceappointment1 = serviceappointmentService.select(serviceappointment_id);
                        return Result.success(serviceappointment1);
                    } else {
                        return Result.error("更新Appointmentslot失败");
                    }
                } else {
                    return Result.error("未找到对应的Appointmentslot记录");
                }
            } else {
                return Result.error("新增失败");
            }
            }
        }
    //删除
    @PostMapping("/delete")
    private Result delete(@RequestParam Integer id) {
        if( serviceappointmentService.delete(id) > 0){
            return Result.success();
        }else {
            return Result.error("删除失败");
        }
    }
    //修改数据
    @PostMapping("/update")
    private Result update(@RequestBody Serviceappointment serviceappointment) {
        if ("已支付".equals(serviceappointment.getStatus())){
            // 更新Serviceappointment记录
            int id = serviceappointment.getId();
            Serviceappointment serviceappointment1 = serviceappointmentService.select(id);
            int appointmentslot_id2 = serviceappointment1.getAppointmentslot_id();
            Appointmentslot appointmentslot2 = appointmentslotService.selectappointmentslot(appointmentslot_id2);
            if (appointmentslot2 != null) {
                // 增加原本的available_spots的数量
                int newAvailableSpots = appointmentslot2.getAvailable_spots() -1;
                appointmentslot2.setAvailable_spots(newAvailableSpots);
                // 更新Appointmentslot对象
                appointmentslotService.updateAppointmentslotById(appointmentslot2);
                int updateResult = serviceappointmentService.update(serviceappointment);
                if (updateResult > 0) {
                    return Result.success("修改成功");
                }else {
                    return Result.error("修改失败");
                }
            }
        }
        // 更新Serviceappointment记录
        int id = serviceappointment.getId();
        Serviceappointment serviceappointment1 = serviceappointmentService.select(id);
        int tk_appointmentslot_id = serviceappointment1.getAppointmentslot_id();
        Appointmentslot appointmentslot1 = appointmentslotService.selectappointmentslot(tk_appointmentslot_id);
        if (appointmentslot1 != null) {
            // 增加原本的available_spots的数量
            int newAvailableSpots = appointmentslot1.getAvailable_spots() + 1;
            appointmentslot1.setAvailable_spots(newAvailableSpots);
            // 更新Appointmentslot对象
            int spotUpdateResult1 = appointmentslotService.updateAppointmentslotById(appointmentslot1);
            if (spotUpdateResult1 > 0) {
                int updateResult = serviceappointmentService.update(serviceappointment);
                if (updateResult > 0) {
                    // 获取Serviceappointment对象中的appointmentslot_id
                    Integer appointmentslotId = serviceappointment.getAppointmentslot_id();

                    // 获取Appointmentslot对象
                    Appointmentslot appointmentslot = appointmentslotService.selectappointmentslot(appointmentslotId);
                    if (appointmentslot != null) {
                        // 减少available_spots的数量
                        int newAvailableSpots1 = appointmentslot.getAvailable_spots() - 1;
                        appointmentslot.setAvailable_spots(newAvailableSpots1);

                        // 更新Appointmentslot对象
                        int spotUpdateResult = appointmentslotService.updateAppointmentslotById(appointmentslot);
                        if (spotUpdateResult > 0) {
                            return Result.success();
                        } else {
                            return Result.error("更新Appointmentslot失败");
                        }
                    } else {
                        return Result.error("未找到对应的Appointmentslot记录2");
                    }
                } else {
                    return Result.error("修改失败");
                }
            } else {
                return Result.error("更新Appointmentslot失败");
            }
        } else {
            return Result.error("未找到对应的Appointmentslot记录1");
        }

    }
    //管理员修改数据
    @PostMapping("/adminupdate")
    private Result adminupdate(@RequestBody Serviceappointment serviceappointment) {
        if ("已支付".equals(serviceappointment.getStatus())){
            // 查询Serviceappointment记录
            int id = serviceappointment.getId();
            Serviceappointment serviceappointment1 = serviceappointmentService.select(id);
            int appointmentslot_id2 = serviceappointment1.getAppointmentslot_id();
            Appointmentslot appointmentslot2 = appointmentslotService.selectappointmentslot(appointmentslot_id2);
            if (appointmentslot2 != null) {
                // 增加原本的available_spots的数量
                int newAvailableSpots = appointmentslot2.getAvailable_spots() -1;
                appointmentslot2.setAvailable_spots(newAvailableSpots);
                // 更新Appointmentslot对象
                appointmentslotService.updateAppointmentslotById(appointmentslot2);
                int user_id = serviceappointment.getUser_id();
                String phone = serviceappointment.getPhone();
                User user = new User();
                user.setId(user_id);
                user.setPhone(phone);
                int updateuser = userService.updatephone(user);
                if (updateuser < 0) {
                    return Result.error("修改失败");
                }
                int updateResult = serviceappointmentService.adminupdate(serviceappointment);
                if (updateResult > 0) {
                    return Result.success("修改成功");
                }else {
                    return Result.error("修改失败");
                }
            }
        }
        // 更新Serviceappointment记录
        int id = serviceappointment.getId();
        Serviceappointment serviceappointment1 = serviceappointmentService.select(id);
        int tk_appointmentslot_id = serviceappointment1.getAppointmentslot_id();
        Appointmentslot appointmentslot1 = appointmentslotService.selectappointmentslot(tk_appointmentslot_id);
        if (appointmentslot1 != null) {
            // 增加原本的available_spots的数量
            int newAvailableSpots = appointmentslot1.getAvailable_spots() + 1;
            appointmentslot1.setAvailable_spots(newAvailableSpots);
            // 更新Appointmentslot对象
            int spotUpdateResult1 = appointmentslotService.updateAppointmentslotById(appointmentslot1);
            if (spotUpdateResult1 > 0) {
                int user_id = serviceappointment.getUser_id();
                String phone = serviceappointment.getPhone();
                User user = new User();
                user.setId(user_id);
                user.setPhone(phone);
                int updateuser = userService.updatephone(user);
                if (updateuser < 0) {
                    return Result.error("修改失败");
                }
                if ("已退款".equals(serviceappointment.getStatus())){
                    int updateResult = serviceappointmentService.adminupdate(serviceappointment);
                    if (updateResult > 0){
                        return Result.success(updateResult);
                    }else {
                        return Result.error("修改失败");
                    }
                }
                int updateResult = serviceappointmentService.adminupdate(serviceappointment);
                if (updateResult > 0) {
                    // 获取Serviceappointment对象中的appointmentslot_id
                    Integer appointmentslotId = serviceappointment.getAppointmentslot_id();

                    // 获取Appointmentslot对象
                    Appointmentslot appointmentslot = appointmentslotService.selectappointmentslot(appointmentslotId);
                    if (appointmentslot != null) {
                        // 减少available_spots的数量
                        int newAvailableSpots1 = appointmentslot.getAvailable_spots() - 1;
                        appointmentslot.setAvailable_spots(newAvailableSpots1);

                        // 更新Appointmentslot对象
                        int spotUpdateResult = appointmentslotService.updateAppointmentslotById(appointmentslot);
                        if (spotUpdateResult > 0) {
                            return Result.success();
                        } else {
                            return Result.error("更新Appointmentslot失败");
                        }
                    } else {
                        return Result.error("未找到对应的Appointmentslot记录2");
                    }
                } else {
                    return Result.error("修改失败");
                }
            } else {
                return Result.error("更新Appointmentslot失败");
            }
        } else {
            return Result.error("未找到对应的Appointmentslot记录1");
        }
    }
    @PostMapping("updatestatus")
    public Result updateStatus(@RequestBody Serviceappointment serviceappointment) {
        if ("退款中".equals(serviceappointment.getStatus())) {
            Serviceappointment existingOrder = serviceappointmentService.select(serviceappointment.getId());
            if (existingOrder == null) {
                return Result.error("订单不存在");
            }
            String currentStatus = existingOrder.getStatus();
            existingOrder.setTk_status(currentStatus);
            if (serviceappointmentService.updatetk_status(existingOrder) > 0) {
                if (serviceappointmentService.updateServiceappointmentstatus(serviceappointment) > 0) {
                    return Result.success("成功");
                } else {
                    return Result.error("数据库更新失败");
                }
            } else {
                return Result.error("更新tk_status失败");
            }
        } else {
            return Result.error("订单状态不允许修改");
        }
    }
    @PostMapping("updateCancel")
    public Result updateCancel(@RequestBody  Serviceappointment serviceappointment) {
        Serviceappointment existingOrder = serviceappointmentService.select(serviceappointment.getId());
        String currentStatus = existingOrder.getTk_status();
        existingOrder.setStatus(currentStatus);
        if (serviceappointmentService.updateServiceappointmentstatus(existingOrder) > 0) {
            return Result.success("取消退款成功");
        }else {
            return Result.error("取消退款失败");
        }
    }
    //管理员批量修改状态
    @PostMapping("/batchUpdateStatus")
    public Result batchUpdateStatus(@RequestBody Map<String, Object> payload) {
        // 从payload中获取orderIds和status
        List<Integer> orderIdList = (List<Integer>) payload.get("ids");
        String newStatus = (String) payload.get("status");

        // 将List转换为int数组
        int[] ids = new int[orderIdList.size()];
        for (int i = 0; i < orderIdList.size(); i++) {
            ids[i] = orderIdList.get(i);
        }
        // 调用service层方法执行批量更新
        int updated = serviceappointmentService.batchUpdateStatus(ids, newStatus);

        // 遍历每个订单ID，根据新状态进行特定操作
        for (Integer orderId : orderIdList) {
            if ("未签到".equals(newStatus) || "已退款".equals(newStatus)) {
                // 查询Serviceappointment记录
                Serviceappointment serviceappointment = serviceappointmentService.select(orderId);
                if (serviceappointment != null) {
                    int appointmentslot_id = serviceappointment.getAppointmentslot_id();
                    Appointmentslot appointmentslot = appointmentslotService.selectappointmentslot(appointmentslot_id);
                    if (appointmentslot != null) {
                        // 根据状态更新available_spots的数量
                        int newAvailableSpots = "未签到".equals(newStatus) ? appointmentslot.getAvailable_spots() - 1 : appointmentslot.getAvailable_spots() + 1;
                        appointmentslot.setAvailable_spots(newAvailableSpots);
                        // 更新Appointmentslot对象
                        appointmentslotService.updateAppointmentslotById(appointmentslot);
                    }
                }
            }
        }
            return updated > 0 ? Result.success("批量更新状态成功") : Result.error("批量更新状态失败");
    }
    //管理员批量删除
    @PostMapping("/admindelete")
    public Result admindelete(@RequestBody Map<String, Object> payload) {
        try {
            // 从payload中获取orderIds
            List<Integer> orderIdList = (List<Integer>) payload.get("ids");
            if (orderIdList == null || orderIdList.isEmpty()) {
                return Result.error("未提供有效的ID列表");
            }

            // 将List转换为int数组
            int[] ids = new int[orderIdList.size()];
            for (int i = 0; i < orderIdList.size(); i++) {
                ids[i] = orderIdList.get(i);
            }

            int affectedRows = serviceappointmentService.admindelete(ids);
            if (affectedRows > 0) {
                return Result.success("删除成功");
            } else {
                return Result.error("删除失败");
            }
        } catch (ClassCastException e) {
            return Result.error("ID列表格式错误，应为整数数组");
        } catch (Exception e) {
            return Result.error("服务器错误：" + e.getMessage());
        }
    }

}
